package io.github.iogogogo.sync.api;

import io.github.iogogogo.commons.util.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

/**
 * Created by tao.zeng on 2025/1/8.
 */
@Slf4j
@RestController
@RequestMapping("/api/index")
public class IndexApi {

    @GetMapping("/bodyEmitter")
    public ResponseBodyEmitter bodyEmitter() {
        // 创建一个ResponseBodyEmitter，-1代表不超时
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();
        // 异步执行耗时操作
        CompletableFuture.runAsync(() -> {
            try {
                // 模拟耗时操作
                for (int i = 0; i < 10; i++) {
                    log.info("bodyEmitter:{}", i);

                    emitter.send("bodyEmitter " + i + " @ " + DateTimeUtils.nowDateTime() + "\n");

                    Thread.sleep(2000);
                }
                // 发送完成
                emitter.complete();
            } catch (InterruptedException | IOException e) {
                // 发生异常，结束接口
                emitter.completeWithError(e);
            }
        });
        return emitter;
    }
}
